package com.shuqi.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.alipay.android.app.util.Utils;
import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.ToastDialog;
import com.shuqi.common.ControlHandler;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.utils.Alipay;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.R;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.PayModel;
import com.shuqi.model.bean.PayAlipayInfo;
import com.shuqi.model.bean.PayItemInfo;
import com.shuqi.model.bean.PayTypeAllInfo;
import com.shuqi.model.bean.PayTypeInfo;
import com.shuqi.model.net.listener.HttpRequestErrListener;
import com.shuqi.swiftp.Globals;

/**
 * 支付宝充值
 * 
 * @author chenwei
 * 
 */
public class PayAlipayActivity extends ActivityBase implements OnClickListener, IEventListener,
        OnItemClickListener, HttpRequestErrListener {
    private final static String TAG = "PayAlipayActivity";

    private LinearLayout mLlError;// 显示网络错误错误的布局
    private TextView mTextRetry;// 网络错误重试

    private PayAlipayInfo mAlipayInfo;// 点击列表项服务器的返回
    private PayTypeInfo mPayTypeInfo;// 服务器返回数据列表的有效项
    private PayTypeAllInfo mPayTypeAllInfo;
    private List<PayItemInfo> mData = new ArrayList<PayItemInfo>();// 有效项的列表数据

    private ListView mLvPaydata;
    private ListCityAdpater mLvAdpater;

    private ActivityManager mActivityManager;
    private PayModel mPayModel;
    private ToastDialog mLoadingDialog;
    /** 进度圈 */
    private LinearLayout mLayoutLoading;
    private CommonTitle mTitle;
    public final static int PAY_ALIPAY_HOME = 0;
    public final static int PAY_ALIPAY_HOME_SUCCESS = 1;
    public final static int PAY_ALIPAY = 2;
    public final static int PAY_HOME_NO_NETWORK = 3;
    public final static int PAY_HOME_INIT = 4;

    private ControlHandler handler = new ControlHandler(this) {

        public void handleMessage(Message msg) {
            // Bundle bundle = msg.getData();

            switch (msg.what) {
                case PAY_HOME_INIT:
                    activityLogicForward();
                    break;
                case PAY_HOME_NO_NETWORK:
                    mLlError.setVisibility(View.VISIBLE);
                    mLayoutLoading.setVisibility(View.GONE);
                    break;
                case PAY_ALIPAY_HOME:
                    mPayModel.getPayDatasByModeId("1");
                    break;
                case PAY_ALIPAY_HOME_SUCCESS:
                    mLayoutLoading.setVisibility(View.GONE);
                    activityInitData();
                    break;
                case PAY_ALIPAY:
                    activityInitDataAlipay();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_pay_alipay);

        mActivityManager = ActivityManager.getInstance();

        mPayModel = new PayModel(this);
        mPayModel.addEventListener(this);

        handler.sendEmptyMessage(PAY_HOME_INIT);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onEvent(int event, Object data) {
        Log4an.d(TAG, "event:" + event + ",result:" + data);
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                if (data != null) {
                    if (data instanceof PayAlipayInfo) {
                        mAlipayInfo = (PayAlipayInfo) data;
                        handler.sendEmptyMessage(PAY_ALIPAY);
                    } else {
                        //List<PayTypeInfo> payTypeInfos = (List<PayTypeInfo>) data;
                        mPayTypeAllInfo = (PayTypeAllInfo)data;
                        if(mPayTypeAllInfo.getPayTypeInfos().size() != 0){
                            mPayTypeInfo = mPayTypeAllInfo.getPayTypeInfos().get(0);
                        }
                        handler.sendEmptyMessage(PAY_ALIPAY_HOME_SUCCESS);
                    }
                }
                break;
            default:
                handler.sendEmptyMessage(PAY_HOME_NO_NETWORK);
                break;
        }
    }

    @Override
    public void activityLogicForward() {
        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);
        this.mLayoutLoading = (LinearLayout) findViewById(R.id.include_loading);
        mLoadingDialog = new ToastDialog(this);
        mLlError = (LinearLayout) findViewById(R.id.include_error);
        mTextRetry = (TextView) findViewById(R.id.retry);
        mTextRetry.setOnClickListener(this);

        mLvPaydata = (ListView) findViewById(R.id.lv_paydata);
        mLvAdpater = new ListCityAdpater(this);
        mLvPaydata.setAdapter(mLvAdpater);
        mLvPaydata.setOnItemClickListener(this);

        handler.sendEmptyMessage(PAY_ALIPAY_HOME);
        this.mLayoutLoading.setVisibility(View.VISIBLE);
    }

    @Override
    public void activityInitData() {
        if(mPayTypeAllInfo == null){
            return;
        }
        if (PayModel.NET_NEEDLOGIN.equals(mPayTypeAllInfo.getCode())) {
            LoginActivity.openVerifyForResult(PayAlipayActivity.this, LoginActivity.LOGINTYPE_VERIFY);
            finish();
        } else if (mPayTypeInfo != null && PayModel.NET_SUCCESS.equals(mPayTypeAllInfo.getCode())) {
            mLlError.setVisibility(View.GONE);
            mData = mPayTypeInfo.getPayItemInfos();
            mLvAdpater.notifyDataSetChanged();
        } else {
            mLoadingDialog.show(false, mPayTypeAllInfo.getMsg());
        }
    }

    /**
     * 点击列表项的返回
     */
    private void activityInitDataAlipay() {
        if (PayModel.NET_NEEDLOGIN.equals(mAlipayInfo.getCode())) {
            LoginActivity.openVerifyForResult(PayAlipayActivity.this, LoginActivity.LOGINTYPE_VERIFY);
            finish();
        } else if (PayModel.NET_SUCCESS.equals(mAlipayInfo.getCode())) {
            Alipay alipay = new Alipay(PayAlipayActivity.this);
            alipay.pay(mAlipayInfo.getPayInfo());
        } else {
            showMsg(mAlipayInfo.getMsg());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.retry:
//                if (!Util.isNetworkConnected(this)) {
//                    return;
//                }
//                this.mLayoutLoading.setVisibility(View.VISIBLE);
//                mLlError.setVisibility(View.GONE);
//                handler.sendEmptyMessage(PAY_ALIPAY_HOME);
                
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {

                    @Override
                    public void netErrorCallback() {
                        mLayoutLoading.setVisibility(View.VISIBLE);
                        mLlError.setVisibility(View.GONE);
                        handler.sendEmptyMessage(PAY_ALIPAY_HOME);

                    }
                });
                break;
            case R.id.title_left:
                mActivityManager.finishActivity(this);
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
        final PayItemInfo payItemInfo = mData.get(position);
        mPayModel.getPayInfo("1", mPayTypeInfo.getTypeId(), payItemInfo.getItemId());
    }

    public final class ViewHolder {
        public TextView price;
        public TextView ppDou;
        public TextView ppName;
        public TextView privilege;
    }

    private class ListCityAdpater extends BaseAdapter {

        private LayoutInflater mInflater;
        private Context context;

        public ListCityAdpater(Context context) {
            this.mInflater = LayoutInflater.from(context);
            this.context = context;
        }

        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {

                holder = new ViewHolder();

                convertView = mInflater.inflate(R.layout.item_pay, null);
                convertView.findViewById(R.id.pay_item).setPadding(Util.dip2px(context, 36), 0, 0, 0);
                
                holder.price = (TextView) convertView.findViewById(R.id.tv_price);
                holder.ppDou = (TextView) convertView.findViewById(R.id.tv_ppDou);
                holder.ppName = (TextView) convertView.findViewById(R.id.tv_ppName);
                holder.privilege = (TextView) convertView.findViewById(R.id.tv_privilege);
                convertView.setTag(holder);

            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            final PayItemInfo payItemInfo = mData.get(position);
            holder.price.setText(payItemInfo.getPrice());
            holder.ppDou.setText(payItemInfo.getPpDou());
            holder.ppName.setText(payItemInfo.getPpDouName());

            if (!"".equals(payItemInfo.getPrivilege())) {
                holder.privilege.setText(getResources().getString(R.string.pay_privilege)
                        + payItemInfo.getPrivilege());

                String privilege = payItemInfo.getPrivilege();

                privilege = privilege.replaceAll("%", "");
                int value = Integer.valueOf(privilege);

                if (value >= 3) {
                    holder.privilege.setBackgroundResource(R.drawable.icon_alipay_3);
                } else {
                    holder.privilege.setBackgroundResource(R.drawable.icon_alipay_1);
                }
                holder.privilege.setVisibility(View.VISIBLE);
            } else {
                holder.privilege.setVisibility(View.INVISIBLE);
            }
            holder.privilege.setPadding(2, 2, 2, 2);

            return convertView;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Globals.setContext(this);

    }

    @Override
    protected void onStop() {
        Globals.setContext(null);
        super.onStop();
    }

    @Override
    public void request_content_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_reponse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_format() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_net_error() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_timeout() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_url() {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            mActivityManager.finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        mData = null;
        super.onDestroy();
    }

}
